package servlet;


import bean.User;
import service.impl.UserServiceImpl;
import utils.DataTypeUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {

    private UserServiceImpl userService = new UserServiceImpl();
//    private static final String loginReq = "login";
//    private static final String registerReq = "register";

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");
        String userPassword = req.getParameter("userPassword");
        User user;
        if((user = userService.login(userId,userPassword)) != null){
            req.getSession().setAttribute("user",user);
            req.getSession().setAttribute("username",user.getUserName());
            req.getSession().setAttribute("userId",user.getId());
//            req.getSession().setAttribute("authority",user.getAuthority());
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        } else {
            req.setAttribute("msg","用户名或密码错误");
            req.setAttribute("userId",userId);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        req.getSession().invalidate();

        resp.sendRedirect(req.getContextPath() + "/pages/client/index.jsp");

    }


    private void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //从界面获取数据
        // 用户编号
        String userId = req.getParameter("userId");
        // 用户名称
        String userName = req.getParameter("username");
        //用户密码
        String password = req.getParameter("password");
        //性别
        String sex = req.getParameter("gender");
        int gender = DataTypeUtils.parseInt(sex, 1);
        // 出生日期
        String data = req.getParameter("data");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date birthday = format.parse(data);

        // 电话
        String phone = req.getParameter("userPhone");
        // 地址
        String address = req.getParameter("userAddress");
        // 注册默认为普通角色
        int userRole = 3;

//        String email = req.getParameter("email");
        //验证码
        String code = req.getParameter("code");

        String sessionCode = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        if(!sessionCode.equalsIgnoreCase(code) || sessionCode == null){
            //验证码错误，跳转回注册页面

            req.setAttribute("msg","验证码错误");
            req.setAttribute("userId",userId);
            req.setAttribute("username",userName);
            req.setAttribute("password",password);


            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
//            System.out.println("code error  " + code);
        } else {
            //判断用户编码是否已存在
            if(!userService.existsUserId(userId)){
                User user = new User();
                user.setUserCode(userId);
                user.setUserName(userName);
                user.setGender(gender);
                user.setUserPassword(password);
                user.setBirthday(birthday);
                user.setPhone(phone);
                user.setAddress(address);
                user.setUserRole(userRole);

                if(userService.registerUser(user)){
                    req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
                } else {
                    System.out.println("register failure");
                    req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
                }
            } else {
                req.setAttribute("msg","用户名已存在");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }
        }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


}
